﻿using LJX.SmartPark.Common.Extensions;
using LJX.SmartPark.Common.ResponseOutput;
using LJX.SmartPark.Domain.IotInfo;
using LJX.SmartPark.Domain.SysManage;
using LJX.SmartPark.EntityFramework;
using LJX.SmartPark.Service.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LJX.SmartPark.Service.SysManage
{
    public class RoleMenuService : IRoleMenuService
    {
        private readonly IRepository<RoleMenu> _studentService;

        private readonly StudentServerContext _context;

        public RoleMenuService(IRepository<RoleMenu> studentService, StudentServerContext context )
        {
            _studentService = studentService;
            _context = context;
        }

        public List<RoleMenu> GetRoleMenuByIdAsync(RoleManage input)
        {
            var result =  _studentService.GetListQuery().Where(x =>x.RoleId == input.Id).ToList();
            return result;
        }

        private async Task<Response<bool>> PostRoleMenu(RoleMenu input)
        {
            var result = _studentService.InsertAsyncById(input.MapTo<RoleMenu>());

            return Response<bool>.Ok(result.Result > 0);
        }

        private int DeleteAllAsync(List<RoleMenu> input)
        {
            _context.RemoveRange(input);
            return _context.SaveChanges();
        }

        public bool PostAddRoleMenu(rolemenu input)
        {
            int count = 0;
            List<RoleMenu> list = _studentService.GetListQuery().Where(x => x.RoleId == input.roleId).ToList();
            if (list.Count == 0)
            {
                foreach (var item in input.menuId)
                {
                    RoleMenu rm = new RoleMenu();
                    rm.Rol_Id = input.roleId;
                    rm.RoleId = input.roleId;
                    rm.MenuId = Convert.ToInt32(item);
                    PostRoleMenu(rm);
                    count++;
                }
                return count > 0;
            }
            else
            {
                DeleteAllAsync(list);
                foreach (var item in input.menuId)
                {
                    RoleMenu rm = new RoleMenu();
                    rm.Rol_Id = input.roleId;
                    rm.RoleId = input.roleId;
                    rm.MenuId = Convert.ToInt32(item);
                    PostRoleMenu(rm);
                    count++;
                }
                return count > 0;
            }
        }
    }
}
